import { wxOauth, getUserFion } from '@/utils/api.js'
export default {
  getUrlPrams(key) {
  		var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)", "i");
  		var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
  		var context = "";
  		if (r != null) {
  			context = r[2];
  		}
  		return context;
  	},
  async init() {
    const vm = this
    var code = this.getUrlPrams("code");
    if (code) {
      vm.getToken(code)
    }else{
      let path = window.location.href.replace(/\?.*#/i, "#") 
      // let path = window.location.href.split('.com')[1]
      // let pathUrl = 'https://app.dev.jinlinjishu.com'+path
      let wxUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' // 授权微信地址
      let LocalAddress = encodeURIComponent(path) // 回调地址
      let appid = 'wxd50cad2e58b2fcaa' // 公众号id
      let state = 1 // 页面传参
      let scope = "snsapi_userinfo" //弹框显示授权
      window.location.href =
      	wxUrl + appid + "&redirect_uri=" + LocalAddress + "&response_type=code&scope=" +
       scope + "&state=" + state +"&connect_redirect=1#wechat_redirect";	
    }
  },
  // 获取微信返回订单openId
  async getToken(code) {
    const vm = this
    const res = await wxOauth({
      code,
      appName: 'shuidisw_mp'
    })
    if (res.access_token) {
      uni.setStorageSync('openId', res.openid)
      vm.getServeToken(res.openid)
    }
  },
  /* 
    用openid换取服务器token
    存储token,存储个人信息
  */
  getServeToken(openid) {
    const vm = this
    uni.request({
      url: 'https://open.jinlinjishu.com/connect/token', //仅为示例，并非真实接口地址。
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      data: {
        appname: 'shuidisw_mp',
        grant_type:"wechat_mp",
        client_id:"open.admin",
        openid
      },
      method: 'POST',
      success: (data) => {
          if (data.data.access_token) {
            const token = 'Bearer ' + data.data.access_token
            uni.setStorageSync('authorization', token)
            vm.getUsser()
          }
        }
    })
  },
  /* 获取个人信息, 存储个人信息 */
  async getUsser() {
    const res = await getUserFion()
    if (res.userName) {
      uni.setStorageSync('userIfon', res)
    }
  }
}